# coding=utf-8 ################################################################
import socketserver
import database
import exchange
import struct
import socket
import utils

class ThreadingTCPServer(socketserver.ThreadingMixIn,
                         socketserver.TCPServer): pass

class RequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        ip_nums = list(map(int, self.client_address[0].split(".")))
        ip = struct.pack("BBBB", ip_nums[0], ip_nums[1], ip_nums[2], ip_nums[3])
        try:
            exchange.do_exchange_server(self.request, ip)
        except utils.ValidateDataError:
            pass

def main():
    db = database.get()
    port, = db.execute("SELECT value FROM misc WHERE name='port'").fetchone()
    db.close()
    server = socketserver.TCPServer(("", int(port)), RequestHandler)    
    server.serve_forever()

if __name__ == '__main__':
    main()
